15.14 Memory Initialization Function
The core entry point for memory initialization is the mm_init() function, which is decorated with the __init attribute and defined within the source file git/init/main.c. Its definition is implemented as follows:
static void __init mm_init(void)
{
page_ext_init_flatmem();
init_debug_pagealloc();
report_meminit();
mem_init();
kmem_cache_init();
kmemleak_init();
pgtable_init();
debug_objects_mem_init();
vmalloc_init();
ioremap_huge_init();
init_espfix_bsp();
pti_init();
}
The function page_ext_init_flatmem() is responsible for allocating memory blocks to accommodate the page extension architecture. If the underlying memory model is configured as a sparse model (SPARSEMEM), this function resolves to a no-operation (no-op). Conversely, if the system relies on a flat memory (FLATMEM) or non-contiguous memory model, it invokes alloc_node_page_ext(). This sub-routine leverages the early boot-stage block memory allocator via memblock_alloc_try_nid() to carve out contiguous memory zones for each individual memory node.
When the system enables the compilation configurations CONFIG_DEBUG_PAGEALLOC and _debug_pagealloc_enabled_early, the function init_debug_pagealloc() sets the underlying enabled fields within the static jump labels _debug_pagealloc_enabled and debug_guardpage_enabled to activate memory page auditing and guard-page safety frameworks.
-
If memory page auditing is successfully energized, when a page is released back to the buddy allocator, the kernel hot-patches its matching page table entry to tag it as non-accessible. If any errant kernel code subsequently attempts to read from or execute an out-of-bounds write to this released page, the CPU instantly flags a hardware violation and triggers a Kernel Panic.
-
If the guard-page framework is active, the kernel embeds non-accessible buffer gaps (Guard Pages) between explicit memory allocations, typically within vmalloc blocks or specialized stack boundaries. If a code execution path suffers a sequential buffer overflow write, the execution pipeline immediately encounters this guard page, causing the CPU to drop into a Page Fault exception due to page table permission violations. This mechanism forces the kernel to generate an immediate Oops report at the precise moment corruption manifests, rather than allowing the data pollution to remain undetected until a catastrophic system crash happens later.
The routine report_meminit() prints diagnostic logs during system boot to report the tracking values utilized when initializing automatic stack variables, heap chunks, and execution stacks. Automatic variables can be initialized to a zero-filled state, and call stacks can similarly be wiped to zero. The kernel data structures can be configured to adopt maximum, intermediate, or baseline protection masks, while heap allocations can be completely zero-filled at the moment of allocation or entirely wiped to zero upon deallocation. This routine generates diagnostic logs formatted similarly to:
mem auto-init: stack:all(zero), heap alloc:on, heap free:off
The function mem_init() is defined within the architecture-specific source file git/arch/arm/mm/init.c. Its technical objective is to scan the global mem_map array and map out the exact boundaries of the residual free space remaining within the system after factoring in early boot allocations. This function primarily performs the following sequential operations:
-
It invokes swiotlb_init() to leverage the early block memory allocator to reserve backing bounce buffers for the SWIOTLB framework, while initializing the underlying data structures consumed by the translation layout.
-
It executes set_max_mapnr() to establish the absolute maximum page frame number tracking limit (max_mapnr) for the system.
-
It utilizes the routine free_unused_memmap() to release unallocated memory tracking metadata blocks (freeing unused zones within the regions mapped out for mem_map).
-
It calls the function memblock_free_all(). This routine flushes the managed_pages counter of every node's struct zone to zero, marks the physical page frames registered as reserved memory inside the device tree with the PG_reserved bitmask (flagging them as unavailable memory), and subsequently transitions all remaining free memory blocks from a reserved state over to a free state by clearing the PG_reserved flag. It then forces the page reference counters to evaluate to 1, and hands these unallocated page frames over to be managed by the buddy allocator infrastructure via __free_pages().
-
It aggregates the total volume of pages freed during step 4 onto the global system memory tracking counter _totalram_pages.
-
It invokes free_highpages() to release all high-memory (HIGHMEM) free physical pages back into the buddy allocator pool, while updating the corresponding tracking counters totalhigh_pages and totalram_pages.
-
It triggers mem_init_print_info() to emit a comprehensive statistical log detailing kernel memory resource utilization metrics.
The function kmem_cache_init() initializes the lookaside slice buffers utilized for dynamic kernel memory allocations. As established across preceding architectural sections, both the SLAB and SLUB allocation engines rely on kmem_cache structures to partition memory blocks that fall beneath a single-page threshold; therefore, the system must initialize the kmem_cache bootstrap registry. Linux implements independent initialization modules tailored specifically to the SLAB and SLUB frameworks, which are hosted within the files git/mm/slab.c and git/mm/slub.c, respectively.
The specific initialization routine executed during the boot phase is determined entirely by compilation flags. If CONFIG_SLAB is enabled, the system executes the routine hosted inside slab.c; if CONFIG_SLUB is configured, it falls back to the routine inside slub.c. The kernel toolchain resolves this path at compile time by auditing the obj-y target specifications listed inside git/mm/Makefile. As previously detailed, the legacy SLAB allocator relies on kmem_cache_node objects to coordinate multi-node memory operations; consequently, the primary technical milestone for the SLAB allocator's version of kmem_cache_init() is to bootstrap these kmem_cache_node data structures. For the SLAB framework, the core operations of kmem_cache_init() encompass:
-
Establishing the three empty slab tracking lists (slabs_full, slabs_partial, and slabs_free) that are mandatory throughout memory allocation passes, and flushing the remaining fields of struct kmem_cache_node to zero.
-
Configuring the global tracking variable slab_max_order governing the limits of slab sizing.
-
Instantiating a specialized bootstrap cache kmem_cache_boot of type struct kmem_cache.
-
Threading this newly created kmem_cache descriptor directly into the global slab_caches circular linked list.
-
Leveraging the function create_kmalloc_cache() to carve out Lookaside buffers specifically allocated to house the struct kmem_cache_node objects.
-
Copying the contents of the early initialization structure init_kmem_cache_node over into the active kmem_cache and kmalloc_caches registries, a routine that internally utilizes kmalloc_node() to dynamically allocate the required backing memory.
-
Instantiating each missing array slot via new_kmalloc_cache() if the cell does not exist, thereby building the comprehensive two-dimensional matrix kmalloc_caches[type][index]. The allocator references this kmalloc_caches[type][index] grid to rapidly resolve and look up a slab memory block of a specific type and magnitude within the slab_caches list.
The function kmemleak_init() bootstraps the built-in automatic memory leak detection module, and its primary operations encompass:
-
Configuring the mandatory baseline age ceiling jiffies_min_age that must transpire following an allocation before leak auditing can safely target that object. Once a block of memory is assigned, the kernel generally requires a small temporal window to write the referencing pointers back into the memory layers. If auditing triggers prematurely before these pointers are committed, kmemleak will falsely flag the object as an orphan leak. By enforcing this constraint, an allocated data object is only integrated into the active scanning and leak reporting pipeline once its continuous lifetime outlasts this threshold.
-
Configuring the execution interval window jiffies_scan_wait that governs the timing loops of the background leak detection daemon thread.
-
Instantiating a lookaside cache object_cache composed of elements of type struct kmemleak_object that is explicitly immune to being tracked by the leak detection logic itself. This repository preserves the crucial metadata tracking descriptors for every chunk of allocated system memory, which the background scanner parses to execute leak evaluations.
-
Instantiating a separate lookaside cache scan_area_cache composed of elements of type struct kmemleak_scan_area that is similarly immune to detection tracking, which is utilized to archive specific sub-regions within a memory block that require precise scanning.
-
Generating tracking metadata records corresponding to the static .data, .bss, and .ro_after_init binary kernel sections, while explicitly tagging these segments as gray. Within the memory leak detector subsystem, memory blocks are categorized into three discrete tracking states: black, gray, and white. A black tag indicates that the memory segment is permanently active and requires no scanning passes. A gray tag denotes that the memory segment is permanently active, but its internal byte payload must be scanned because it potentially encloses pointer references targeting auxiliary memory modules. A white tag signifies that the object status is pending; if an object remains trapped in the white state when a comprehensive parsing sweep concludes, it is officially classified as a memory leak.
The function pgtable_init() calls the routines ptlock_cache_init() and pgtable_cache_init() to bootstrap the lookaside caches dedicated to tracking page table locks alongside architecture-specific page table blocks.
-
To prevent resource contention and thread synchronization bottlenecks across multi-core architectures, Linux relies extensively on a diverse family of locks. The routine ptlock_cache_init() instantiates a specialized kmem_cache allocation pool designated as page->ptl to facilitate the high-efficiency allocation and tracking of these page table locks. This lookaside cache is structured as a collection of kmem_cache descriptors, and its base address is tracked via the pointer variable page_ptl_cachep.
-
The function pgtable_cache_init() initializes the architecture-dependent page validation structures. For 64-bit ARM platforms, if the physical magnitude of the Page Global Directory (PGD) differs from the native hardware page size, the routine carves out a specialized kmem_cache lookup buffer named pgd_cache; conversely, for 32-bit ARM architectures, this function resolves to a no-operation (no-op) block.
The function debug_objects_mem_init() sets up the core tracking infrastructures consumed by the object lifecycle validation subsystem (debug_objects). Its central task is to instantiate a primary memory pool designated as debug_objects_cache. This memory pool is reserved to house the debug_obj structure nodes that preserve the lifecycle metadata of every tracked object. Furthermore, debug_objects_mem_init() establishes a localized, per-CPU hash table for each individual processor core to store its own active debug_obj elements. To minimize inter-core locking contention and optimize execution path speeds, each CPU additionally manages a localized mini-pool containing a subset of debug_obj structures reserved exclusively for its own real-time tasks.
The function vmalloc_init(void) prepares the framework-level configuration required to transition the system from basic physical memory tracking over to full virtual memory allocation management, serving as the foundational architectural prerequisite for subsequent calls to vmalloc(), vmap(), and ioremap(). Its primary technical objective is to establish and map out the precise virtual address space boundaries utilized by the vmalloc() subsystem. The core operational milestones of vmalloc_init() encompass:
-
Instantiating a lookaside cache named vmap_area composed of elements of type struct vmap_area. The base memory address tracking pointer for this cache is specified as vmap_area_cachep.
-
Initializing the individual structural fields of the vmap_block_queue structures assigned to each CPU core. To minimize lock contention across distinct processor cores during high-frequency virtual memory allocations, Linux allocates a small pool of per-CPU private memory structures of type struct vmap_block to track the metadata of the vmap_area instances consumed locally by that core. This structure encapsulates fields including local spinlocks, a pointer referencing the specific underlying vmap_area block, flags logging whether the cached slot resides in a vacant state, and an embedded list tracking available free blocks. The vmap_block_queue container manages two primary tracking members: a spinlock and the list head anchoring the unallocated vmap_block elements.
-
Initializing the per-CPU tracking structure vfree_deferred utilized to handle deferred memory deallocations. This tracking structure encapsulates a deferred reclamation list head along with a work_struct task block that maps out the background execution thread responsible for freeing the memory. Under numerous runtime execution conditions, a vmap_area allocation block consumed by a running process cannot be safely or instantly released. Under this constraint, the target memory block is shunted onto the deferred reclamation list referenced by the vfree_deferred context, and is subsequently drained and released at a more topologically appropriate time by the asynchronous processing worker free_work().
-
Converting all legacy vm_struct allocation elements preserved within the early vmlist list over into the modern descriptor format utilized by the vmap_area engine, and transferring these nodes to consolidate vmalloc region tracking under a centralized management scheme.
-
Traversing all allocated virtual memory blocks recorded across the vmap_area_list tracking chain. By executing a comprehensive sweep across this list, the initialization routing maps out the available vacant spaces inside the vmalloc window. It aggregates these free segments into a centralized interval red-black tree rooted at free_vmap_area_root, while concurrently threading the sequential list tracking fields of these unallocated vmap_area blocks onto a linear list headed by the symbol free_vmap_area_list.
The function ioremap_huge_init() initializes the operational bitmask flags that dictate whether the system is permitted to leverage huge pages (where PMDs support 2 MiB blocks and PUDs accommodate 1 GiB blocks) during heavy I/O memory mapping allocations. These tracking capability parameters encompass ioremap_p4d_capable, ioremap_pud_capable, and ioremap_pmd_capable, and their availability depends on the specific hardware architecture of the underlying processor.
The function init_espfix_bsp() represents a specialized hot-patch routine embedded within the Linux kernel to mitigate the microarchitectural Intel x86_64 hardware CPU bug surrounding the handling of the ESP stack pointer register; for ARM-based processor architectures, this initialization routine resolves to an empty function block.
The routine pti_init() serves as the final sub-routine executed at the conclusion of the mm_init() sequence. pti_init() represents the core initialization handler for the Kernel Page Table Isolation (KPTI) mechanism, a defense infrastructure introduced to mitigate the catastrophic Meltdown processor vulnerability. The central design philosophy of this framework is to enforce strict boundaries restricting the visible memory map exposed to user space. When a process executes within user space, the page translation tables mask out the kernel address space, exposing only a minimal, strictly necessary subset of kernel helper addresses. The full, unrestricted address space mapping topology is securely restored only when the process explicitly transitions back into kernel-space execution through a system call or hardware exception vector.